﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Rung.EBook.DocFormater.Umd;
using System.IO;

namespace Rung.EBook.UI.Controls.Panels
{
    public partial class pnChmMaker : UserControl
    {
        private WriteInfo mWriteInfo;
        private AppendInfo mAppendInfo;
        private UmdBookBM mBookBM = new UmdBookBM();
        private string mTemplateHtml;
        private Dictionary<string, string> mTemplates;

        public pnChmMaker()
        {
            InitializeComponent();
        }

        internal pnChmMaker(WriteInfo mWriteInfo, AppendInfo mAppendInfo)
            : this()
        {
            this.mWriteInfo = mWriteInfo;
            this.mAppendInfo = mAppendInfo;
        }

        private void pnChmMaker_Load(object sender, EventArgs e)
        {
            this.Dock = DockStyle.Fill;

            this.mTemplates = new Dictionary<string, string>();

            BindingSource bs = new BindingSource();
            bs.DataSource = this.LoadTemplates();
            this.cbTemplate.DataSource = bs;
            this.cbTemplate.DisplayMember = "Key";
            this.cbTemplate.ValueMember = "Value";
        }

        private void btnOpenProject_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog dialog = new OpenFileDialog())
            {
                dialog.Title = "载入工程";
                dialog.CheckPathExists = true;
                dialog.Multiselect = false;
                dialog.DefaultExt = "ebp";
                dialog.Filter = "RungEBook项目文件|*.ebp";
                dialog.InitialDirectory = Rung.EBook.Common.Driver.StaticFunctions.GetProjectFolderPath();

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = dialog.FileName;

                    try
                    {
                        this.mBookBM.LoadByProject(filePath);

                        this.mWriteInfo("载入工程成功。", InfoType.Success);
                        this.RenderByBookBM();
                    }
                    catch (Exception ex)
                    {
                        this.mWriteInfo("载入工程失败：" + ex.Message, InfoType.Errer);
                    }
                }
            }
        }

        // 将 mBook 变量中的值赋予界面控件。
        private void RenderByBookBM()
        {
            //tbAuthor.Text = this.mBookBM.Author;
            //tbBookTitle.Text = this.mBookBM.Title;
            //tbGender.Text = this.mBookBM.Kind;
            //tbPublisher.Text = this.mBookBM.Publisher;
            //tbVendor.Text = this.mBookBM.Vendor;

            lbChapters.Items.Clear();
            foreach (ChapterBM bm in this.mBookBM.Chapters)
            {
                lbChapters.Items.Add(bm);
            }
        }

        private void btnSaveProject_Click(object sender, EventArgs e)
        {

        }

        private void lbChapters_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lbChapters.SelectedIndex < 0) return;

            ChapterBM cBM = lbChapters.SelectedItem as ChapterBM;
            if (cBM != null)
            {
                string bookTitle = string.IsNullOrEmpty(this.mBookBM.Title) ? string.Empty : this.mBookBM.Title;
                string content = Rung.EBook.Common.Driver.StaticFunctions.TxtToHtml(cBM.Content);

                // 创建临时文件名
                FileInfo temp = new FileInfo(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".htm"));
                // 写入临时文件
                File.WriteAllText(temp.FullName, string.Format(this.mTemplateHtml, bookTitle, cBM.Title, content), this.mBookBM.Encoding);

                wbContent.Navigate(temp.FullName);
            }
        }

        // 获取现有模板
        private Dictionary<string, string> LoadTemplates()
        {
            string templatePath = Rung.EBook.Common.Driver.StaticFunctions.GetTemplateFolderPath();

            DirectoryInfo di = new DirectoryInfo(templatePath);
            FileInfo[] fii = di.GetFiles("*.htm", SearchOption.TopDirectoryOnly);
            foreach (FileInfo fi in di.GetFiles("*.htm", SearchOption.TopDirectoryOnly))
            {
                this.mTemplates.Add(fi.Name, fi.FullName);
            }

            return this.mTemplates;
        }

        private string GetTemplate(string fileName)
        {
            return this.mTemplates[fileName];
        }

        // 模板选择
        private void cbTemplate_SelectedIndexChanged(object sender, EventArgs e)
        {
            KeyValuePair<string, string> pair = (KeyValuePair<string, string>)cbTemplate.SelectedValue;
            this.mTemplateHtml = File.ReadAllText(pair.Value);
        }

        // 上一页
        private void btnPreChapter_Click(object sender, EventArgs e)
        {
            if (lbChapters.SelectedIndex > 0)
                lbChapters.SelectedIndex--;
        }

        // 下一页
        private void btnNextChapter_Click(object sender, EventArgs e)
        {
            if (lbChapters.SelectedIndex < lbChapters.Items.Count - 1)
                lbChapters.SelectedIndex++;
        }

        // 页面按键
        private void wbContent_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Left)
                this.btnPreChapter_Click(sender, e);
            else if (e.KeyCode == Keys.Right)
                this.btnNextChapter_Click(sender, e);
        }
    }
}
